package com.swan.security.security;

import com.swan.security.domain.SecurityUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/** 通过用户名查询用户详情
 * @author zongf
 * @date 2025-02-19
 */
@Slf4j
public class SecurityUserDetailSupplier implements UserDetailsService {

    @Autowired
    private IUserSelector userSelector;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("查询用户信息:{}", username);
        // 查询用户详情
        SecurityUserInfo securityUserInfo = this.userSelector.selectByUsername(username);
        if(securityUserInfo == null){
            // security 会将 UsernameNotFoundException 异常转换为 BadCredentialsException 异常。 所以需要 自定义 BadCredentialsExceptionHandler
            throw new UsernameNotFoundException(username);
        }
        return securityUserInfo;
    }

}
